package com.intco.ait.quotation.api.infrastructure.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.intco.ait.quotation.api.common.model.BomInfoDTO;
import com.intco.ait.quotation.api.common.model.PackageMethodVo;
import com.intco.ait.quotation.api.common.model.request.PackageSearchVo;
import com.intco.ait.quotation.api.common.utils.UIDGenerator;
import com.intco.ait.quotation.api.infrastructure.mybatis.entity.BomDetailDo;
import com.intco.ait.quotation.api.infrastructure.mybatis.entity.BomTemplateDo;
import com.intco.ait.quotation.api.infrastructure.mybatis.entity.PackageMethodDo;
import com.intco.ait.quotation.api.infrastructure.mybatis.service.BomDetailService;
import com.intco.ait.quotation.api.infrastructure.mybatis.service.PackageMethodService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PackageService {

    @Autowired
    private PackageMethodService packageMethodService;

    @Autowired
    private BomDetailService bomDetailService;

    @Autowired
    private BomService bomService;

    @Autowired
    private UIDGenerator uidGenerator;


    public Page<PackageMethodVo> search(PackageSearchVo packageSearch) {
        QueryChainWrapper<PackageMethodDo> query = packageMethodService.query();
        if (StringUtils.isNotBlank(packageSearch.getName())) {
            query.like("name", packageSearch.getName());
        }
        if (StringUtils.isNotBlank(packageSearch.getStatus())) {
            query.eq("status", packageSearch.getStatus());
        }
        Page<PackageMethodDo> packageMethodDoPage = query.orderByDesc("insert_time")
                .page(new Page<>(packageSearch.getPage(), packageSearch.getPageSize()));
        List<PackageMethodVo> packageVos = packageMethodDoPage.getRecords().stream().map(packageDo -> {
            PackageMethodVo packageVo = new PackageMethodVo();
            packageVo.setId(packageDo.getId());
            packageVo.setName(packageDo.getName());
            packageVo.setPic(packageDo.getPic());
            packageVo.setBomS(bomService.getBomSForSku(JSON.parseArray(packageDo.getBomDetailIds(), Long.class)));
            packageVo.setStatus(packageDo.getStatus());
            packageVo.setCreateTime(packageDo.getInsertTime());
            packageVo.setUpdateTime(packageDo.getUpdateTime());
            return packageVo;
        }).collect(Collectors.toList());

        return new Page<PackageMethodVo>(packageMethodDoPage.getCurrent(), packageMethodDoPage.getSize(), packageMethodDoPage.getTotal())
                .setRecords(packageVos);
    }

    public void createPackage(PackageMethodVo packageMethodVo) {
        boolean exist = packageMethodService.query().eq("name", packageMethodVo.getName()).exists();
        if (exist) {
            throw new IllegalArgumentException("PackageMethod name already exists");
        }
        PackageMethodDo packageMethodDo = new PackageMethodDo();
        packageMethodDo.setId(uidGenerator.nextId());
        packageMethodDo.setName(packageMethodVo.getName());
        packageMethodDo.setPic(packageMethodVo.getPic());
        List<BomInfoDTO> bomS = packageMethodVo.getBomS();
        List<Long> bomIds = new ArrayList<>();
        bomS.forEach(bomInfo -> {
            BomTemplateDo existBom = bomService.getBomTemplateByName(bomInfo.getBom().getName());
            Long newBomId = null;
            if (existBom == null) {
                newBomId = bomService.creatBom(bomInfo.getBom());
            }
            Long bomId = Objects.isNull(newBomId) ? existBom.getId() : newBomId;
            long bomDetailId = bomService.initBomDetailId(bomInfo, packageMethodDo.getId(), bomId);
            bomIds.add(bomDetailId);
        });
        packageMethodDo.setBomDetailIds(JSON.toJSONString(bomIds));
        packageMethodService.save(packageMethodDo);
    }

    public void update(PackageMethodVo packageMethodVo) {
        PackageMethodDo packageMethodDo = packageMethodService.getById(packageMethodVo.getId());
        if (packageMethodDo == null) {
            throw new IllegalArgumentException("PackageMethod does not exist");
        }
        List<BomInfoDTO> bomS = packageMethodVo.getBomS();
        List<BomDetailDo> bomDetailDos = bomDetailService.query().eq("belong_id", packageMethodVo.getId()).list();
        Set<Long> newBomIdS = bomService.handleAddBomForBelong(packageMethodVo.getId(), bomS, bomDetailDos);
        packageMethodDo.setBomDetailIds(JSON.toJSONString(newBomIdS));
        packageMethodDo.setStatus(packageMethodVo.getStatus());
        packageMethodDo.setUpdateTime(new Date());
        packageMethodService.updateById(packageMethodDo);
    }
}
